import React, { useState, useEffect } from "react";
import "./ProMent.scss";
import "./ProFrom.scss";
import {
  Button,
  DatePicker,
  Input,
  Modal,
  Form,
  notification,
  Table,
  message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  PlusOutlined,
  CaretDownOutlined,
  SendOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import * as service from "../../../../api/cgg/index";
import { number } from "echarts";
function ProMent() {
  const { RangePicker } = DatePicker;
  const { Search } = Input;
  async function onChange(value: any, dateString: any) {
    var res = await service.findAllProductByTime({
      page: 1,
      limit: 20,
      starttime: dateString[0],
      endtime: dateString[1],
    });
    res.data.data.records.forEach((item: any, index: any) => {
      item.key = index;
    });
    setData(res.data.data.records);
    console.log(res.data.data);
  }
  const [open, setOpen] = useState(false);
  function onOk(value: any) {
    console.log("onOk: ", value);
  }
  const onFinish = async (values: any) => {
    console.log("Success:", values);
    var res = await service.addProduct(values);
    console.log(res);
    if (res.data.code == 200) {
      notification.success({ message: res.data.msg });
      let newData = JSON.parse(JSON.stringify(data))
      newData.push(values)
      newData.forEach((item: any, index: any) => {
        item.key = index;
      });
      setData(newData)
    }

    setOpen(false);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  var handleSerch = async (value: any) => {
    var res = await service.findAllProductByCode({
      page: 1,
      limit: 10,
      code: value,
    });
    console.log(res);
    res.data.data.records.forEach((item: any, index: any) => {
      item.key = index;
    });
    setData(res.data.data.records);
  };

  var [data, setData] = useState([]);
  useEffect(() => {
    var getfindAllProduct = async () => {
      var res = await service.findAllProduct({ page: "1", limit: "100" });
      console.log(res.data.data.records);
      res.data.data.records.forEach((item: any, index: any) => {
        item.key = index;
      });
      setData(res.data.data.records);
      setUpdata(res.data.data.records.productState)
      console.log(res.data.data.records[0].productState);
    };
    getfindAllProduct();
  }, []);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  interface DataType {
    key: React.Key;
    name: string;
    age: number;
    address: string;
    pro: any;
  }

  const columns: ColumnsType<DataType> = [
    {
      key: "img",
      title: "图片",
      // dataIndex: "img",
      render: (records) => <img src={records.productPic} alt="" />,
    },
    {
      key: "name",
      title: "名称",
      dataIndex: "productName",
    },
    {
      key: "pro",
      title: "产品线",
      dataIndex: "productLine",
    },
    {
      key: "crate",
      title: "品类",
      dataIndex: "productType",
    },
    {
      key: "time",
      title: "创建时间",
      dataIndex: "productCreattime",
    },
    {
      key: "flag",
      title: "状态",
      dataIndex: "flag",
      render: (_: any, record: any, index: any) => {
        if (record.productState === 1) {
          return (
            <span className="state">
              <span className="zt">·</span>
              下架
            </span>
          );
        } else {
          return (
            <span className="state">
              <span className="active">·</span>
              上架
            </span>
          );
        }
      },
    },
    {
      key: "bj",
      title: "是否上架",
      dataIndex: "bj",
      render: (_: any, record: any, index: any) => (
        <CaretDownOutlined
          onClick={() => handleUpdate(record)}
          rotate={num}
          style={{ color: "yellow", fontSize: "30px" }}
        />
      ),
    },
    {
      key: "sj",
      title: "删除",
      dataIndex: "sj",
      render: (_: any, record: any) => (
        <DeleteOutlined
          onClick={() => flag(record.productId)}
          style={{ color: "red", fontSize: "25px" }}
        />
      ),
    },
  ];
  const [num,setNum] = useState(0)
  const [updata,setUpdata]=useState(number)
  const [open1, setOpen1] = useState(false);
  var flag = async (productId: any) => {
    console.log(productId);

    var res = await service.deleteProduct({ pid: productId });
    console.log(productId);
    
    if (res.data.code == 200) {
      var newData = JSON.parse(JSON.stringify(data));
      var i: any = newData.findIndex(
        (item: any) => item.productId == productId
      );
      if (i != -1) {
        newData.splice(i, 1);
        setData(newData);
      }
      notification.success({ message: "删除成功" });
    } else {
      notification.error({ message: "删除失败" });
    }
  };
  var handleUpdate = (record: any) => {
    if (record.productState === 1) {
      record.productState = 0;

      setUpdata(record.productState)
    } else if(record.productState === 0){
      record.productState =1;
   
      setUpdata(record.productState)
    }
    console.log(record.productState);
  };
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;
  const onFinish1 = (values: any) => {
    console.log("Success:", values);
  };

  const onFinishFailed1 = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <div className="App">
      <header className="App-header">
        <div className="left">
          <Button
            type="default"
            onClick={() => setOpen(true)}
            icon={<PlusOutlined />}
          >
            新增产品
          </Button>
          {/* <Button className="btn" type="default" icon={<SendOutlined />}>
            推送
          </Button> */}
        </div>
        <div className="right">
          <RangePicker
            className="rang"
            style={{ width: 220 }}
            showTime={{ format: "HH:mm" }}
            format="YYYY-MM-DD HH:mm"
            placeholder={["开始时间", "结束时间"]}
            onChange={onChange}
            onOk={onOk}
          />
          <Search
            style={{ width: 220 }}
            placeholder="请输入产品相关编码"
            enterButton="搜索"
            onSearch={(value) => handleSerch(value)}
          />
        </div>
      </header>
      <main className="main">
        <div style={{ marginBottom: 16 }}>
          <span style={{ marginLeft: 8 }}>
            {hasSelected ? `Selected ${selectedRowKeys.length} items` : ""}
          </span>
        </div>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={data}
        />
      </main>
      <Modal title="新增产品" footer={null} open={open} width={1000}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="图片"
            name="productPic"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="名称"
            name="productName"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="创建时间"
            name="productCreattime"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="产品线"
            name="productLine"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="品类"
            name="productType"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" onClick={() => setOpen(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              新增
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="修改产品"
        centered
        open={open1}
        onOk={() => setOpen1(false)}
        onCancel={() => setOpen1(false)}
        width={750}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish1}
          onFinishFailed={onFinishFailed1}
          autoComplete="off"
        >
          <Form.Item
            label="图片地址"
            name="productPic"
            rules={[{ required: true, message: "输入内容不能为空！！！" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="Password"
            name="password"
            rules={[{ required: true, message: "输入内容不能为空！！！" }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              修改
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default ProMent;
